# -*- coding: UTF-8 -*-
# @Time : 2022/1/17 0017 17:14
# @Author : lyw
# @Remark : 门禁
from mxsoftpy import Server

from db.common.IOTManager.Janitor.door import SelectDoorDB, GetRECDoorDB
from model.common.IOTManager.Janitor.door import GetRECDoorModel, DoorModel
from utils.classes.custom_exception import VerifyError
from utils.public.params_method import get_pagination_params, pagination

from index import _


class GetDoorInfoServer(Server):
    __db__ = SelectDoorDB

    def get_door_info(self, *, origin_id="", search_door="", pageindex="", pagesize, **kwargs):
        """
        获取门禁数据
        *为占位符 表示必须有后面几个键名固定的键值对, 如果没有就报错
        :param origin_id: 数据源ID -->int
        :param search_door: 搜索内容    -->str
        :param pageindex: 页码    -->int
        :param pagesize: 每页显示数量 -->int
        :param kwargs: 无意义参数 -->dict
        :return:
        """

        """query_condition：查询条件"""
        # query_condition = {'origin_id': origin_id, 'search_door': search_door, 'pageindex': pageindex,
        query_condition = {'origin_id': ".".join(["data_origin", origin_id]) if origin_id else "",
                           'search_door': search_door, 'pageindex': pageindex,
                           'pagesize': pagesize}

        if kwargs.get('type'):
            """
            如果有type_id为导出excel,为门禁显示请求 导出全部数据, 
            如果以后查看门禁需要导出 只需要改此下面的kwargs['origin_id'],分页需要改paging
            """
            """规范格式"""
            query_condition['search_door'] = query_condition['search_door'] if query_condition.get(
                'search_door') else ''
            query_condition['origin_id'] = ''
            paging = {}

            """导出数据"""
            data_all = self.db.get_door_all(paging, **query_condition)
            res_dict = {"data": data_all[1]}
            return res_dict
        else:
            """
            没有为正常的门禁显示和查看门禁页面请求
            """

            """分页校验"""
            paging = get_pagination_params(query_condition)
            """数据库操作"""
            data_all = self.db.get_door_all(paging, **query_condition)
            """整理数据"""
            """res_dict:为分页编写的数据格式"""
            res_dict = {"data": data_all[1], "total": data_all[0]}
            door_data_list = pagination(res_dict, paging, data_all[0])

        return door_data_list


class GetRECDoorServer(Server):
    __db__ = GetRECDoorDB
    __model__ = GetRECDoorModel

    def get_rec_door(self, **kwargs):
        """
        获取门禁列表
        @param kwargs: search_door 搜索字段 host 根据ip定位门禁 model_id 模板id
        @return:
        """
        # origin_data = self.model(host=kwargs["host"],model_id=kwargs["model_id"]).dict()
        origin_data = self.model(host=kwargs.get("host", ""), model_id=kwargs.get("model_id", "")).dict()
        search_door = kwargs["search_door"].replace("*", "") if kwargs.get("search_door") else ""
        if search_door:
            origin_data["label__like"] = "*" + search_door + "*"

        origin_data["is_del"] = 0
        return self.db.query_rec_door(**origin_data)


class SelectDoorServer(Server):
    __db__ = SelectDoorDB
    __model__ = DoorModel

    def update(self, *args, **kwargs):
        return self.db.update(*args, **kwargs)

    def create(self, *args, **kwargs):
        return self.db.create(*args, **kwargs)

    def select_door(self, **kwargs):
        """
        选择门禁
        @param kwargs:  host 根据ip定位门禁 door_id 所选择门禁的列表
        @return:
        """
        rec_door = self.db.select_rec_door(host=kwargs["host"])
        # 缓存 door_id
        door_dict = self.db.get_door(host=kwargs["host"])
        door_list = []
        for door_id in kwargs["door_id"].split(","):
            door_id = "rec_door." + door_id
            if not door_id:
                continue
            if door_id not in rec_door:
                raise VerifyError(_("参数%s不存在..." % door_id))
            door_list.append(door_id)
        if not door_list:
            raise VerifyError(_("选择门禁是空的"))
        res_list = []
        num = 0
        origin_data = self.db.query_origin(host=kwargs["host"])
        # 未采集的门
        rec_door_list = self.db.query_rec_door(is_switch=rec_door)
        # 打开door
        # self.db.open_door()
        for door in rec_door_list:
            door_sub_key = door_dict.get(door["rec_id"], "")
            door["origin_id"] = origin_data[0]
            door["model_id"] = origin_data[1]["model_id"]
            door_data = self.model(**door).dict()
            if door["rec_id"] in door_list:
                if door_sub_key:
                    door_data["is_del"] = 0
                    res_list.append(self.update(door_sub_key, **door_data))
                else:
                    res_list.append(self.create(**door_data))
                num += 1
            else:
                if door_sub_key:
                    door_data["is_del"] = 1
                    self.update(door_sub_key, **door_data)
                else:
                    continue
        self.db.update_origin(origin_data[0], count=num)
        return ",".join(res_list)
